package com.bx.imclient.sender;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.spring.client.MqttClientTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * @author wsq
 */
@Slf4j
@Service
public class MqttClientService {
    @Value("mqtt.client.clientId")
    String clientId;

    @Resource
    private MqttClientTemplate client;

    /**
     * 往mqtt推送消息
     *
     * @param receiceUserId 接收人id
     * @param body          消息体
     * @return bool
     */
    public boolean publishPrivateMessage(Long receiceUserId, String body) {
        String topic1 = "/user/message/%d";
        String topic = String.format(topic1, receiceUserId);
        client.publish(topic, body.getBytes(StandardCharsets.UTF_8));
        log.info("发送消息，topic: " + topic + "," + body);
        return true;
    }

    public boolean publishGroupMesssage(Long groupId, String body) {
        String topic1 = "/group/message/%d";
        String topic = String.format(topic1, groupId);
        client.publish(topic,body.getBytes(StandardCharsets.UTF_8));
        return true;
    }

    /**
     * 订阅消息
     *
     * @return b
     */
    public boolean sub() {
        client.subQos0("/message/" + clientId, (context, topic, message, payload) -> {
            log.info(topic + '\t' + new String(payload, StandardCharsets.UTF_8));
        });
        return true;
    }

}
